import multer from 'multer';
import path from 'path';
import fs from 'fs';
import winston from 'winston';
import crypto from 'crypto';

// 创建logger实例
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      )
    })
  ]
});

// 配置磁盘存储
const diskStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = './uploads/medical_images';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const timestamp = Date.now();
    const randomString = crypto.randomBytes(4).toString('hex');
    const ext = path.extname(file.originalname);
    const filename = `temp_${timestamp}_${randomString}${ext}`;
    cb(null, filename);
  }
});

// 创建multer实例
const fixedUpload = multer({
  storage: diskStorage,
  limits: {
    fileSize: 15 * 1024 * 1024, // 15MB
    files: 1
  }
});

// 简化的文件上传中间件
export const uploadMedicalImage = async (req, res, next) => {
  try {
    // 添加调试日志
    logger.info('🔍 文件上传调试信息:', {
      headers: req.headers,
      bodyFields: Object.keys(req.body || {}),
      files: req.files || 'no files',
      file: req.file ? {
        originalname: req.file.originalname,
        fieldname: req.file.fieldname,
        mimetype: req.file.mimetype,
        size: req.file.size
      } : 'no file'
    });

    // 使用multer处理文件上传
    fixedUpload.single('image')(req, res, async (err) => {
      if (err) {
        logger.error('文件上传错误:', {
          error: err.message,
          code: err.code,
          originalname: req.file?.originalname,
          ip: req.ip,
          userAgent: req.get('User-Agent')
        });

        // 删除临时文件
        if (req.file && req.file.path) {
          try {
            fs.unlinkSync(req.file.path);
            logger.info('文件删除成功:', req.file.path);
          } catch (deleteError) {
            logger.error('文件删除失败:', deleteError);
          }
        }

        return res.status(400).json({
          success: false,
          message: '文件上传失败',
          data: null,
          error_code: err.code || 'UPLOAD_ERROR'
        });
      }

      // 检查是否有文件上传
      if (!req.file) {
        return res.status(400).json({
          success: false,
          message: '未选择文件',
          data: null,
          error_code: 'NO_FILE_UPLOADED'
        });
      }

      try {
        // 基础文件验证
        logger.info('开始文件基础验证:', {
          originalname: req.file.originalname,
          mimetype: req.file.mimetype,
          size: req.file.size,
          path: req.file.path
        });

        // 检查文件大小
        if (req.file.size > 15 * 1024 * 1024) {
          throw new Error('文件过大，请控制在15MB以内');
        }

        // 检查文件类型
        const allowedTypes = ['image/jpeg', 'image/png', 'image/bmp', 'image/tiff'];
        if (!allowedTypes.includes(req.file.mimetype)) {
          throw new Error('不支持的文件类型，请上传图像文件');
        }

        // 生成安全的文件名
        const timestamp = Date.now();
        const randomString = crypto.randomBytes(8).toString('hex');
        const ext = path.extname(req.file.originalname);
        const secureFilename = `medical_${timestamp}_${randomString}${ext}`;
        const newPath = path.join(path.dirname(req.file.path), secureFilename);

        // 重命名文件
        fs.renameSync(req.file.path, newPath);
        req.file.filename = secureFilename;
        req.file.path = newPath;

        logger.info('文件上传和验证完成:', {
          filename: req.file.filename,
          originalname: req.file.originalname,
          size: req.file.size,
          mimetype: req.file.mimetype
        });

        // 继续处理请求
        next();
      } catch (validationError) {
        // 验证失败，删除文件
        if (req.file && req.file.path) {
          try {
            fs.unlinkSync(req.file.path);
            logger.info('文件删除成功:', req.file.path);
          } catch (deleteError) {
            logger.error('文件删除失败:', deleteError);
          }
        }

        logger.warn('文件验证失败:', {
          originalname: req.file.originalname,
          error: validationError.message,
          ip: req.ip
        });

        return res.status(400).json({
          success: false,
          message: validationError.message,
          data: null,
          error_code: 'VALIDATION_ERROR'
        });
      }
    });
  } catch (error) {
    logger.error('上传中间件错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器内部错误',
      data: null,
      error_code: 'SERVER_ERROR'
    });
  }
};
